/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.ventas;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.bean.FiltroNC;
import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Demanda;
import dp1.titandevelop.titano.persistent.NotaCredito;
import dp1.titandevelop.titano.persistent.NotaCredito;
import dp1.titandevelop.titano.service.NotaCreditoService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.awt.Dimension;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author heli
 */
public class ModulosT_VEN_ANC extends javax.swing.JInternalFrame {
    public ModulosT_VEN_ADNuevo nuevo=null;
    public ModulosT_VEN_ADEdit editar=null;
    public ModulosT_VEN_ANCDetalle detalle=null;
    public FiltroNC busqueda=null;
    private Mensajes sms = new Mensajes();
    
    
    /**
     * Creates new form TitanoInteralSegADMUser
     */
    public ModulosT_VEN_ANC() {
        initComponents();
        
        this.inhabilitaBotones();
        Estado state=new Estado();
        this.cboxEstado.addItem(state.devuelveCadena(state.getEnUso()));
        this.cboxEstado.addItem(state.devuelveCadena(state.getSinUsar()));
        
        
        ValidacionService validacionService = new ValidacionService();
        validacionService.SLetras(this.txtRazonSocial);
        validacionService.NoEscribe(this.txtFechaInicio);
        validacionService.NoEscribe(this.txtFechaFin);
    }

      public List<NotaCredito> notas = null;
    //metodo para refrescar la tabla
      
    public void habilitaBotones(){
        //this.btnEditarA.setEnabled(true);
        this.btnEliminarA.setEnabled(true);
        //this.btnDetalle.setEnabled(true);
    }
    private void inhabilitaBotones(){
       // this.btnEditarA.setEnabled(false);
        this.btnEliminarA.setEnabled(false);
        //this.btnDetalle.setEnabled(false);
    }
    
    public FiltroNC filtro(){
        FiltroNC df=new FiltroNC();
        Estado state=new Estado();
        df.setRazonSocial(this.txtRazonSocial.getText());
        df.setFechaIni(this.txtFechaInicio.getDate());
        df.setFechaFin(this.txtFechaFin.getDate());
        df.setEstado(state.getEstadoId(this.cboxEstado.getSelectedItem().toString()));
        
        return df;
    }
    
    public void llenarFiltro(FiltroNC df){
        Estado state=new Estado();
        this.txtRazonSocial.setText(df.getRazonSocial());
        this.txtFechaInicio.setDate(df.getFechaIni());
        this.txtFechaFin.setDate(df.getFechaFin());
        this.cboxEstado.setSelectedItem(state.devuelveCadena(df.getEstado()));
        
        
    }
    
    public void  buscar(FiltroNC dF){
       NotaCreditoService serv = new NotaCreditoService();
       notas = serv.buscarNotaCredito(dF);
        
        this.actualizarNotaCreditoList();
    }
    
    Thread actualizarnotacredito = null;
    private void actualizarNotaCreditoList(){
        if( actualizarnotacredito!=null && actualizarnotacredito.isAlive() ){
            actualizarnotacredito.interrupt();
        }
        actualizarnotacredito = new Thread( new Runnable() {
            @Override
            public void run() {
                RefreshTable();
                ModeloTabla modelo= new ModeloTabla();
                tableResultados.setModel(modelo);
                
            }
        });
        actualizarnotacredito.start();
    }
    
    
    public void RefreshTable() {
        
        AbstractTableModel aux = (AbstractTableModel)tableResultados.getModel();
        aux.fireTableDataChanged();
    }
    
    class ModeloTabla extends AbstractTableModel {  
        //Atributos de los datos de la tabla
        private String [] titles = {"Fecha", "Cliente/Razón Social","Descripción","Monto","Motivo","Estado"};
        //private List<DataTabla> datos;
        //private Object [][]datos;
        
        public int getRowCount() {
            return notas.size();
        }      
        
        public int getColumnCount() {
            return 6; // cuantas columnas
        }          
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }                
       
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            NotaCredito p = notas.get(rowIndex);
            
            switch(columnIndex){
                case 0: res = p.getFecha(); break;
                case 1: res = p.getToDocumentoVenta().getContacto(); break;
                case 2: res = p.getDescripcion(); break;
                case 3: res = p.getMonto(); break;
                case 4:  if(p.getTipo()==1){ res="Devolución"; }else{ res="Anulación" ; }break;
                case 5: res = Estado.devuelveCadena(p.getEstado()); break;
                
            }
            return res;
        } 
        //Ultima celda editable para selección
        @Override
        public boolean isCellEditable(int row, int col) {
            boolean res=false;
            switch (col) {
                case 0:break;
                case 1:break;
               // case 2:res=true;
            }
            return res;
        }
        //para obtener las clases de cada celda y asi mostrar estas correctamente
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
//        @Override
//        public void setValueAt(Object value, int row, int col) {
//            datos.get(row).seleccionado = (Boolean)value;
//        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        txtRazonSocial = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtFechaInicio = new org.jdesktop.swingx.JXDatePicker();
        jLabel7 = new javax.swing.JLabel();
        txtFechaFin = new org.jdesktop.swingx.JXDatePicker();
        cboxEstado = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableResultados = new javax.swing.JTable();
        btnBuscar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        btnEliminarA = new javax.swing.JButton();
        btnDetalle = new javax.swing.JButton();

        setResizable(true);
        setTitle("Administrar Nota de Credito");
        setPreferredSize(new java.awt.Dimension(650, 550));
        setVisible(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de Búsqueda"));
        jPanel1.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        jLabel9.setText("Razon Social");

        jLabel13.setText("Estado");

        jLabel5.setText("Fecha Inicio");

        jLabel7.setText("Fecha Fin");

        cboxEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));
        cboxEstado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboxEstadoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel9))
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtRazonSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel13))
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cboxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(62, 62, 62))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(txtFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRazonSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(jLabel13)
                    .addComponent(cboxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultado de Búsqueda"));
        jPanel2.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        tableResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Fecha", "Cliente/Razón Social", "Descripción", "Monto", "Motivo", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                true, true, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableResultados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableResultadosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableResultados);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addGap(6, 6, 6))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        btnBuscar.setToolTipText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/limpiar.png"))); // NOI18N
        btnLimpiar.setToolTipText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/retroceder.png"))); // NOI18N
        btnSalir.setToolTipText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnEliminarA.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminarA.setToolTipText("Eliminar");
        btnEliminarA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarAActionPerformed(evt);
            }
        });

        btnDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/detalle.png"))); // NOI18N
        btnDetalle.setToolTipText("Ver Detalle");
        btnDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnBuscar)
                                .addGap(1, 1, 1)
                                .addComponent(btnLimpiar)
                                .addGap(0, 0, 0)
                                .addComponent(btnSalir)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnDetalle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminarA)))
                .addGap(8, 8, 8))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnDetalle)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnBuscar)
                            .addComponent(btnLimpiar)
                            .addComponent(btnSalir))
                        .addGap(8, 8, 8)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(8, 8, 8)
                        .addComponent(btnEliminarA)))
                .addContainerGap(68, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnEliminarAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarAActionPerformed
        int confirmar = JOptionPane.showInternalConfirmDialog(this.getRootPane(),"¿Está seguro que desea eliminar el registro?","Aviso!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);

        if (JOptionPane.OK_OPTION == confirmar)
        {//Obtengo el objeto seleccionado
            NotaCreditoService serv = new NotaCreditoService();
            NotaCredito nc = notas.get(this.tableResultados.getSelectedRow());
            this.notas.remove(this.tableResultados.getSelectedRow());
            
            serv.eliminar(nc.getIdnotacredito());
        }

        this.RefreshTable();
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnEliminarAActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        FiltroNC dF=new FiltroNC();
        dF=this.filtro();
        this.buscar(dF);
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        txtRazonSocial.setText("");
       cboxEstado.setSelectedIndex(0);
       txtFechaInicio.setDate(null);
       txtFechaFin.setDate(null);
       notas.clear();
       this.RefreshTable();
       this.inhabilitaBotones();
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void tableResultadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableResultadosMouseClicked
        if(evt.getClickCount()==1){
            this.habilitaBotones();
        }
    }//GEN-LAST:event_tableResultadosMouseClicked

    private void cboxEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboxEstadoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cboxEstadoActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
       
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleActionPerformed
        try{
            NotaCredito sol;
            FiltroNC busqueda=null;
            busqueda=this.filtro();
            sol = notas.get(this.tableResultados.getSelectedRow());
            //Instancio la ventana
            detalle= new ModulosT_VEN_ANCDetalle(sol,busqueda,2);
            this.getParent().add(detalle);

            Dimension desktopSize = this.getParent().getSize();
            Dimension jInternalFrameSize = detalle.getSize();
            detalle.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,(desktopSize.height - jInternalFrameSize.height)/4 );
            detalle.show();

            //Inhabilito los botones una vez realizada la acción
            this.inhabilitaBotones();
        }catch(Exception e){
            JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
        }
        this.dispose();
    }//GEN-LAST:event_btnDetalleActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnDetalle;
    private javax.swing.JButton btnEliminarA;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cboxEstado;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableResultados;
    private org.jdesktop.swingx.JXDatePicker txtFechaFin;
    private org.jdesktop.swingx.JXDatePicker txtFechaInicio;
    private javax.swing.JTextField txtRazonSocial;
    // End of variables declaration//GEN-END:variables

    private void setLocationRelativeTo(Object object) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private Object getparent() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
